﻿using Inovout.Cloud.Messager.Domain;
using Inovout.Component;
using Inovout.Data.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Inovout.Cloud.Messager.Service
{
    public class MessageService
    {
        private static IRepositoryService<Message> service;
        public MessageService()
        {
            service = ComponentRegistry.Resolve<IRepositoryService<Message>>();
        }

        public void SenderMessage(Message Msg, string TemplateId)
        {
            Msg.Templates = MessageTemplateService.GetMessageTemplate(Msg.UserId, TemplateId);
            Msg.Content = GetContext(Msg.Templates.Content, Msg.Content);
            InsertMsg(Msg);
            if ((Msg.Transmit & TransmitMethod.Html) != 0)
            {
                SendMessageService.Sender += SendMessageService.HtmlSender;
            }
            SendMessageService.SenderMsg(Msg);
        }

        public string GetContext(string Parameters, string Content)
        {
            string[] SParameters = Parameters.Split(',');
            foreach (string Parameter in SParameters)
            {
                string[] Arr = Parameter.Split('=');
                Content.Replace(Arr[0], Arr[1]);
            }
            return Content;
        }

        public void InsertMsg(Message Msg)
        {
            service.Save(Msg);
        }

        #region 根据参数
        //private Message GetMsg(string UserId, string Recipients, string TemplateId, string Parameters)
        //{
        //    Message Msg = new Message();
        //    Msg.UserId = UserId;
        //    Msg.Recipients = Recipients;
        //    Msg.Templates = MessageTemplateService.GetMessageTemplate(UserId, TemplateId);
        //    Msg.Content = GetContext(Parameters, Msg.Templates.Content);
        //    return Msg;
        //}
        //public void SenderMessage(string UserId, string Recipients, string TempId, string Parameters)
        //{
        //    Message Msg = GetMsg(UserId, Recipients, TempId, Parameters);
        //    InsertMsg(Msg);
        //    if ((Msg.Transmit & TransmitMethod.Html) != 0)
        //    {
        //        SendMessageService.Sender += SendMessageService.HtmlSender;
        //        SendMessageService.SenderMsg(Msg);
        //    }
        //} 
        #endregion
    }
}
